import lrz from 'lrz'
/*
 * OssToken 缓存
 */
function getClient(uploaddir){
  var OssClient=window.localStorage.getItem("ossClient");
  var OssExpire=window.localStorage.getItem("ossExpire");
    if (OssClient == null||OssExpire==null||(new Date()-OssExpire)>0) {
      return Promise.resolve(axios.post('/fcs-api/getOssStsToken', '{"uploaddir":"'+uploaddir+'"}', {headers: {'Content-Type': 'application/json;charset=UTF-8'}}).then((result) => {
        const client = new OSS.Wrapper({
          region: 'oss-cn-shanghai-finance-1-pub',
          accessKeyId: result.data.policy.accessid,
          accessKeySecret: result.data.policy.signature,
          stsToken: result.data.policy.policy,
          bucket: result.data.policy.bucket
        })
        if(client!=null){
        window.localStorage.setItem("ossExpire",new Date(result.data.policy.expire));
        window.localStorage.setItem("ossClient",client);
        return client;
      }
    }))
      ;
    }
    return Promise.resolve(OssClient);
}

/**
 * 上传图片
 */
function put(client,file,uploaddir){
  const storeAs = file.name;
  return Promise.resolve(lrz(file, {quality: 0.8}).then((results) => {
     var reader = new FileReader();
     reader.readAsArrayBuffer(results.file);
     reader.onload = function (event) {
     var buffer = new OSS.Buffer(event.target.result);
     return client.put(uploaddir, buffer);
    }
  }))
}

/**
 * 保存图片
 */
function afterUpload(uploaddir,url){
  if(uploaddir==null||url==null){
    return null;
  }
  var arr =uploaddir.split("/");
  var obj=new Object();
  obj['category2']=arr[3];
  obj['category1']=arr[2];
  obj['createId']='sysadmin';
  obj['instNo']=arr[0];
  obj['orderNo']=arr[1];
  obj['mediaUrl']=url;
  //保存图片
  return Promise.resolve(axios.post('/fcs-api/afterUpload', JSON.stringify(obj), {headers: {'Content-Type': 'application/json;charset=UTF-8'}}).then((result) => {
        return result;
  }))
}

function upload(uploaddir,file){
  var client=null;
  getClient().then((result)=>{
    put(result,file,uploaddir).then((result)=>{

      afterUpload(uploaddir,)
  })
  })
}

export default {getClient}
